package com.samuel.basics.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Optional;

/**
 * <p>JackJSON  工具类</p>
 *
 * @author aneng huang
 * @since 2020-12-25 11:01:52
 */
public class JsonUtil {

    static ObjectMapper objectMapper;

    /**
     * 解析json
     *
     * @param content    内容
     * @param valueType 解析的类型
     * @return  该类型的内容
     */
    public static <T> T fromJson(String content, Class<T> valueType) {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }
        try {
            return objectMapper.readValue(content, valueType);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成json
     *
     * @param object  内容
     * @return  字符串
     */
    public static Optional<String> toJson(Object object) {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }
        try {
            String s = objectMapper.writeValueAsString(object);
            return Optional.ofNullable(s);
        } catch (Exception e) {
            e.printStackTrace();
            return Optional.empty();
        }

    }


}
